package com.dxt.service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.dxt.common.AppConstant;
import com.dxt.common.LogHelper;
import com.dxt.common.MyBusiException;
import com.dxt.message.AppRequestMessage;
import com.dxt.message.ReponseMessage;
import com.dxt.netty.RuiKongYdServerHandler;
import com.dxt.netty.utils.CRC16Util;
import com.dxt.netty.utils.ReqStrUtils;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Random;

@Service("ResetControlService")
public class RKResetControlService extends IBaseBusiService {
    private static final Logger logger = LoggerFactory.getLogger(Thread.currentThread().getStackTrace()[1].getClassName());

    @Autowired
    CacheManager cacheManager;

    @Override
    public ReponseMessage execute(String reqInfo, String url) {
        logger.debug(LogHelper._FUNC_START_());
        ReponseMessage message = new ReponseMessage();
        AppRequestMessage msg = getMsg();
        JSONObject jsonObject = JSON.parseObject(reqInfo);
        try {
            /**
             * 校验必填业务参数是否为空
             */
            checkParams(jsonObject, AppConstant.REQUEST_REPONSE_PARAM.PARAM_IN_DEVICEID,
                    AppConstant.REQUEST_REPONSE_PARAM.PARAM_IN_RESETCONTROL_TYPE);
        } catch (MyBusiException e) {
            message.setMsg(AppConstant.REPONSE_CODE.BUSI_ERROR, AppConstant.REPONSE_MSG.SYS_PARAM_ERROR_MSG,
                    e.getMessage());
            return message;
        }
        Channel channel = RuiKongYdServerHandler.getChannel(jsonObject.getLong(AppConstant.REQUEST_REPONSE_PARAM.PARAM_IN_DEVICEID));
        if(channel == null){
            message = message.getReponseMessage(jsonObject,message);
            return message;
        }
        //将其转换为十六进制并输出
        String strHex = Long.toHexString(jsonObject.getLong(AppConstant.REQUEST_REPONSE_PARAM.PARAM_IN_DEVICEID)).toUpperCase();
        logger.debug("strHex = " + ReqStrUtils.transHex((strHex)));
        int random = new Random().nextInt(10);
        String signStr = "";
                String tripControlType = jsonObject.getString(AppConstant.REQUEST_REPONSE_PARAM.PARAM_IN_RESETCONTROL_TYPE);
        if("0".equals(tripControlType)){
            signStr = "="+random+"Y5"+ReqStrUtils.transHex((strHex))+",R1000000000,";
        }else if("1".equals(tripControlType)){
            signStr = "="+random+"Y5"+ReqStrUtils.transHex((strHex))+",R1000000010,";
        }
        message = message.getReponseMessage(signStr,channel,jsonObject,message);
        return message;
    }

}
